package com.gitee.huxing.course.util;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.BeanWrapper;
import org.springframework.beans.BeanWrapperImpl;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.HashSet;
import java.util.Set;


/**
 * @Description: spring上下文工具类
 * @ProjectName: JavaCourse
 * @Package: com.gitee.huxing.course.netty.util
 * @ClassName: SpringBeanContext
 * @Author: huxing
 * @DateTime: 2021-08-21 下午5:40
 */
@Slf4j
@Component
public class SpringBeanContext implements ApplicationContextAware{

    private static ApplicationContext ctx;

    @Override
    synchronized public void setApplicationContext(ApplicationContext appContext) throws BeansException {
        log.info("预加载容器类:  {}" , LocalDateTime.now());
        ctx = appContext;
    }

    public static ApplicationContext getApplicationContext() {
        return ctx;
    }

    /**
     * @Description:  根据bean名称获取bean，如果获取不到返回NULL
     * @Author: huxing
     * @param name
     * @return java.lang.Object
     * @Date: 2021-07-14 10:45
     **/
    public static Object getBean(String name){
        return getApplicationContext().getBean(name);
    }

    /**
     * 根据bean class获取bean
     * @param clazz
     * @return
     */
    public static <T> T getBean(Class<T> clazz){
        return getApplicationContext().getBean(clazz);
    }

    /**
     * 根据bean名称和bean class获取bean
     * @param name
     * @param clazz
     * @return
     */
    public static <T> T getBean(String name, Class<T> clazz){
        return getApplicationContext().getBean(name, clazz);
    }

    /**
     * copy变量忽略NULL字段
     *
     * @param src
     * @param desc
     */
    public static void copyProperties(Object src, Object desc){
        BeanUtils.copyProperties(src, desc, getNullPropertyNames(src));
    }

    /**
     * 忽略非空字段
     * @param source
     * @return
     */
    public static String[] getNullPropertyNames (Object source) {
        final BeanWrapper src = new BeanWrapperImpl(source);
        java.beans.PropertyDescriptor[] pds = src.getPropertyDescriptors();

        Set<String> emptyNames = new HashSet<String>();
        for(java.beans.PropertyDescriptor pd : pds) {
            Object srcValue = src.getPropertyValue(pd.getName());
            if (srcValue == null) {
                emptyNames.add(pd.getName());
            }
        }
        String[] result = new String[emptyNames.size()];
        return emptyNames.toArray(result);
    }

    /**
     *
     * @param objs
     * @return
     */
    public static <T> T getInstanceBean(T t,Object... objs){
        for (Object obj : objs){
            SpringBeanContext.copyProperties(obj, t);
        }
        return t;
    }
}
